<script>
import { mapState } from 'vuex';

export default {
  name: 'enterpriseForm',
  props: {
    edit: {
      type: Boolean,
      required: true,
    },
  },
  data() {
    return {
      /* 表单数据对象 */
      formParams: {
        name: '',
        legalPerson: '',
        industryCode: '',
        registeredAddress: '',
        businessLicenseUrl: '',
        businessLicenseId: '',
        contact: '',
        contactNumber: '',
      },
      /* 表单规则对象 */
      formRules: {
        name: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
        legalPerson: [{ required: true, message: '请输入法人代表', trigger: 'blur' }],
        industryCode: [{ required: true, message: '请选择所在行业', trigger: 'change' }],
        registeredAddress: [{ required: true, message: '请输入注册地址', trigger: 'blur' }],
        businessLicenseId: [{ required: true, message: '请上传营业执照' }],
        contact: [{ required: true, message: '请输入企业联系人', trigger: 'blur' }],
        contactNumber: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
      },
      fileList: [],
    };
  },
  methods: {
    /* 获取所在行业列表的回调函数 */
    async fetchIndustryList() {
      try {
        await this.$store.dispatch('enterpriseStore/fetchIndustryList');
      } catch (error) {
        this.$message.error(error.message);
      }
    },
    /* 更新企业的回调函数 */
    async updateEnterprise() {
      try {
        delete this.formParams.businessLicenseName;
        delete this.formParams.industryName;
        delete this.formParams.rent;
        const updateResult = await this.$store.dispatch('enterpriseStore/updateEnterprise', this.formParams);
        this.$message.success(updateResult);
        this.$emit('success');
      } catch (error) {
        this.$message.error(error.message);
      }
    },
    /* 添加企业的回调函数 */
    async addEnterprise() {
      try {
        const addResult = await this.$store.dispatch('enterpriseStore/addEnterprise', this.formParams);
        this.$message.success(addResult);
        this.$emit('success');
      } catch (error) {
        this.$message.error(error.message);
      }
    },
    /* 查找企业的回调函数 */
    async findEnterprise(id) {
      try {
        const formParams = await this.$store.dispatch('enterpriseStore/findEnterprise', id);
        this.formParams = { ...formParams };
        this.fileList = [{ name: formParams.businessLicenseName, url: formParams.businessLicenseUrl }];
      } catch (error) {
        this.$message.error(error.message);
      }
    },
    /* 上传文件超出个数限制时的钩子 */
    handleExceed() {
      this.$message.warning('只能上传一张图片');
    },
    /* 上传文件之前的钩子  */
    beforeUpload(file) {
      const isImage = file.type.startsWith('image');
      const isLt2M = file.size / 1024 / 1024 < 2;
      return isImage && isLt2M;
    },
    /* 文件列表移除文件时的钩子 */
    removeUpload() {
      this.formParams.businessLicenseUrl = '';
      this.formParams.businessLicenseId = '';
      this.formParams.businessLicenseName = '';
      this.fileList = [];
      this.$refs.formRef.validateField('businessLicenseId');

    },
    /* 覆盖默认的上传行为，自定义上传的回调函数 */
    async handleRequest({ file }) {
      try {
        const formData = new FormData();
        formData.append('file', file);
        formData.append('type', '1');
        const { id, url } = await this.$store.dispatch('enterpriseStore/upload', formData);
        this.formParams.businessLicenseId = id;
        this.formParams.businessLicenseUrl = url;
        this.$message.success('上传文件成功');
        this.$refs.formRef.validateField('businessLicenseId');
      } catch (error) {
        this.$message.error(error.message);
      }
    },
    /* 点击确定按钮的回调函数 */
    async handleSubmit() {
      const valida = await this.$refs.formRef.validate().catch(error => error);
      if (!valida) return;
      if (this.edit) {
        await this.updateEnterprise();
      } else {
        await this.addEnterprise();
      }
    },
    /* 清空数据的回调函数 */
    async resetForm() {
      this.$refs.formRef.resetFields();
    },
  },
  computed: {
    ...mapState('enterpriseStore', ['industryList']),
  },
  emits: ['success'],
  created() {
    this.fetchIndustryList();
  },
};
</script>

<template>
  <el-form label-width="100px" :model="formParams" :rules="formRules" ref="formRef">
    <el-form-item label="企业名称" prop="name">
      <el-input size="amll" placeholder="请输入企业名称" v-model="formParams.name"></el-input>
    </el-form-item>
    <el-form-item label="法人代表" prop="legalPerson">
      <el-input size="amll" placeholder="请输入法人代表" v-model="formParams.legalPerson"></el-input>
    </el-form-item>
    <el-form-item label="注册地址" prop="registeredAddress">
      <el-input size="amll" placeholder="请输入注册地址" v-model="formParams.registeredAddress"></el-input>
    </el-form-item>
    <el-form-item label="所在行业" prop="industryCode">
      <el-select size="amll" v-model="formParams.industryCode" placeholder="请选择所在行业">
        <el-option v-for="(item) in industryList" :value="item.industryCode" :label="item.industryName" :key="item.industryCode"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="企业联系人" prop="contact">
      <el-input size="amll" placeholder="请输入企业联系人" v-model="formParams.contact"></el-input>
    </el-form-item>
    <el-form-item label="联系电话" prop="contactNumber">
      <el-input size="amll" placeholder="请输入联系电话" v-model="formParams.contactNumber"></el-input>
    </el-form-item>
    <el-form-item label="营业执照" prop="businessLicenseId">
      <el-upload class="upload-demo" action="#" :limit="1" :file-list="fileList" :before-upload="beforeUpload" :http-request="handleRequest" :on-exceed="handleExceed" :on-remove="removeUpload">
        <el-button size="small" :type="formParams.businessLicenseId?'success':'primary'" :icon="`${formParams.businessLicenseId?'el-icon-check':'el-icon-upload'}`">{{ formParams.businessLicenseId ? '上传成功' : '点击上传' }}</el-button>
      </el-upload>
    </el-form-item>
    <el-form-item>
      <el-button size="small">取消</el-button>
      <el-button size="small" type="primary" @click="handleSubmit">确定</el-button>
    </el-form-item>
  </el-form>
</template>

<style scoped lang="scss">
.el-form {
  width: 80%;

  .el-select {
    width: 100%;
  }
}
</style>
